#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include <time.h>
#include <stdlib.h>

osThreadId_t task_1_id;
osThreadId_t task_2_id;
osThreadId_t task_3_id;
osEventFlagsId_t event_id;

// 设置事件标志
void Task1(void *arg){
    while(1){
        osEventFlagsSet(event_id, 0x01);
        printf("[Task1]Set event 0x01\n");
        sleep(1);
        osEventFlagsSet(event_id, 0x02);
        printf("[Task1]Set event 0x02\n");
        sleep(1);
        osEventFlagsSet(event_id, 0x04);
        printf("[Task1]Set event 0x04\n");
        sleep(1);
    }
}

// 接受3个事件标志后执行，执行完后产生第4个事件标记
void Task2(void *arg){
    while(1){
        osEventFlagsWait(event_id, 0x07, osFlagsWaitAll, osWaitForever);
        osEventFlagsSet(event_id, 0x08);
        printf("[Task2]Set event 0x08\n");
        sleep(1);
    }
}

// 在第4个事件标记后执行，执行完后清除所有事件标记
void Task3(void *arg){
    while(1){
        osEventFlagsWait(event_id, 0x08, osFlagsWaitAny, osWaitForever);
        osEventFlagsClear(event_id, 0x08);
        osEventFlagsClear(event_id, 0x04);
        osEventFlagsClear(event_id, 0x02);
        osEventFlagsClear(event_id, 0x01);
        printf("[Task3]Clear all event\n");
    }
}

void event_demo(){
    osThreadAttr_t attr1={
        .name="task1",
        .stack_size=1024*4,
        .priority=osPriorityNormal,
    };
    osThreadAttr_t attr2={
        .name="task2",
        .stack_size=1024*4,
        .priority=osPriorityNormal,
    };
    osThreadAttr_t attr3={
        .name="task3",
        .stack_size=1024*4,
        .priority=osPriorityNormal,
    };

    event_id=osEventFlagsNew(NULL);
    if(event_id==NULL){
        printf("event_id create failed");
    }
    else{
        printf("event_id is %d",event_id);
    }

    task_1_id=osThreadNew(Task1,NULL,&attr1);
    if(task_1_id==NULL){
        printf("[Task1]task_1_id create failed");
    }
    else{
        printf("[Task1]task_1_id is %d",task_1_id);
    }

    task_2_id=osThreadNew(Task2,NULL,&attr2);
    if(task_2_id==NULL){
        printf("[Task2]task_2_id create failed");
    }
    else{
        printf("[Task2]task_2_id is %d",task_2_id);
    }

    task_3_id=osThreadNew(Task3,NULL,&attr3);
    if(task_3_id==NULL){
        printf("[Task3]task_3_id create failed");
    }
    else{
        printf("[Task3]task_3_id is %d",task_3_id);
    }
}

SYS_RUN(event_demo);
